package com.zyf.lj.service.impl;

import com.zyf.lj.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    private final Path fileStorageLocation;

    public FileServiceImpl(@Value("${file.upload}") String uploadDir) {
        this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception ex) {
            throw new RuntimeException("无法创建上传目录！", ex);
        }
    }

    @Override
    public String storeFile(MultipartFile file) throws IOException {
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String extension = StringUtils.getFilenameExtension(originalFilename);
        String filename = UUID.randomUUID().toString() + (extension != null ? "." + extension : "");
        Path targetLocation = this.fileStorageLocation.resolve(filename);
        file.transferTo(targetLocation);
        return filename;
    }

    @Override
    public Resource loadFileAsResource(String filename) throws IOException {
        Path filePath = this.fileStorageLocation.resolve(filename).normalize();
        Resource resource = new FileSystemResource(filePath);
        if (resource.exists()) {
            return resource;
        } else {
            throw new IOException("文件未找到 " + filename);
        }
    }

    @Override
    public String getOriginalFilename(String storedFilename) {
        // 在此实现中，我们不存储原始文件名，因此此方法返回存储的文件名
        // 如果需要存储原始文件名，可以在 storeFile 方法中保存到数据库或另一个文件
        return storedFilename;
    }
} 